package com.chiemy.cardview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hs.ble.LeDeviceListAdapter;
import com.hs.color.lamp.BluetoothChatService;
import com.hs.spp.ota.CommCmd;
import com.hs.spp.ota.TransOverSpp;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Semaphore;

@SuppressLint("NewApi")
public class SPPOTAFragment extends Fragment{

	
	// Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST_CONN_LOST = 5;
    // Message types sent from the Trans Handler
    public static final int MESSAGE_SPP_OTA_SUCCESS = 1;
    public static final int MESSAGE_SPP_OTA_FAILED  = 2;
    public static final int MESSAGE_PBAR_INI        = 3;
    public static final int MESSAGE_UPDATE_PBAR     = 4;
    public static final int MESSAGE_ERASE_SUCCESS     = 5;
    public static final int MESSAGE_ERASE_FAILED     = 6;
    
    
    public static BluetoothChatService mChatService = null;
    public TransOverSpp transSPP = null;
    
    private String tag = "SPPOTAFragment";
    public static String TOAST = "toast";
    private List<BluetoothDevice> mconnectedDevices = null;
	private TextView tv;
	private Button downloadBtn;
	private Button erasedBtn;
	private Button appBtn;
	private Button use_eraseBtn;
	private View root;
	private View view;
	private Context context;
	private boolean mScanning;
	private static final long SCAN_PERIOD = 10000;
	private ListView lv;
	private LeDeviceListAdapter mDeviceListAdapter;
	private Handler mHandler;
	private BluetoothAdapter mClassicAdapter;
	public static boolean mClassicConnected = false;
	private int m_isA2dpConnected = -1;
	
	private int APP_FILE_SELECT_CODE = 0;
	private Uri m_appfile_uri = null;
	private ProgressBar pb;
	public BluetoothDevice mDevice;
	protected String mDeviceAddress;
	private  Semaphore erase_doenload_lock = new Semaphore(1);

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.context=activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		root = inflater.inflate(R.layout.spp_ota_frag_layout, container,false);
		initUI(root);
		
		mDeviceListAdapter = new LeDeviceListAdapter((Activity) context);
		
		lv.setAdapter(mDeviceListAdapter);
		mHandler = new Handler();
		
		//classic
		mClassicAdapter = BluetoothAdapter.getDefaultAdapter();
		if(mClassicAdapter == null) 
		{
			Toast.makeText(context, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
			return root;
		}


		if(!mClassicAdapter.isEnabled()) 
		{
			Toast.makeText(context, "请打开您的蓝牙设备，然后重新打开软件！！.", Toast.LENGTH_LONG).show();
			return root;

		}
		context.registerReceiver(searchDevices, classicUpdateIntentFilter());
		//mClassicAdapter.startDiscovery();
		mChatService = new BluetoothChatService(context, mSPPHandler);
		context.registerReceiver(DevicesState, makeDevicesStateIntentFilter());
		
		m_isA2dpConnected = mClassicAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
		if(m_isA2dpConnected == BluetoothProfile.A2DP)
		{
			// TODO get a2dp profixy and get the connected device 
 		   	mClassicAdapter.getProfileProxy(context, A2DPListener, BluetoothProfile.A2DP);
     	    
		}
		transSPP = new TransOverSpp(mChatService);
		return root;
	}
	
	private static IntentFilter makeDevicesStateIntentFilter() {
		 final IntentFilter intentFilter = new IntentFilter();
		 intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
	     intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
		 intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		 intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		 
		 //intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		 return intentFilter;
	}
	
	private BroadcastReceiver DevicesState = new BroadcastReceiver() { 

       public void onReceive(Context context, Intent intent) {

           String action = intent.getAction();
           if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
           {
        	   Toast.makeText(context, " disconnect !!!", Toast.LENGTH_SHORT).show();
        	   mClassicConnected = false;
        	   downloadBtn.setEnabled(false);
           	   erasedBtn.setEnabled(false);
        	   return ;
           }
           if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
           {
        	   ((Activity) context).setProgressBarIndeterminateVisibility(false);
           }
           
           if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))
           {
        	   ((Activity) context).setProgressBarIndeterminateVisibility(true);
           }
           
       }   

    };
	
	//a2dp call back
	private  BluetoothProfile.ServiceListener A2DPListener = new  BluetoothProfile.ServiceListener(){
	
		@Override
		public void onServiceConnected(int profile, BluetoothProfile proxy) {
			// TODO Auto-generated method stub
			BluetoothA2dp a2dp = (BluetoothA2dp) proxy;
			BluetoothA2dp mA2DP = a2dp;
			Toast.makeText(context, "A2DP service connected!", Toast.LENGTH_SHORT).show();
			//TODO
			if(m_isA2dpConnected == BluetoothProfile.A2DP)
			{
				mconnectedDevices = mA2DP.getConnectedDevices();
				 
			}
			
        	
		}
	
		@Override
		public void onServiceDisconnected(int profile) {
			// TODO Auto-generated method stub
			
		}
		
		
	};
	private final Handler mSPPHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                Log.i(tag, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                	Toast.makeText(context, R.string.title_connected, Toast.LENGTH_SHORT).show();
 	        	    Toast.makeText(context, "spp connect success!!!", Toast.LENGTH_SHORT).show();

                	mClassicConnected  = true;
                	downloadBtn.setEnabled(true);
                	erasedBtn.setEnabled(true);
                	use_eraseBtn.setEnabled(true);
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                	Toast.makeText(context, R.string.title_connecting, Toast.LENGTH_SHORT).show();
                    
                    break;
                case BluetoothChatService.STATE_LISTEN:
                	
                	break;
                case BluetoothChatService.STATE_NONE:
                	Toast.makeText(context, R.string.title_not_connected, Toast.LENGTH_SHORT).show();
                	
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                
                break;
            case MESSAGE_READ:
            	int arg1 = msg.arg1;
                byte[] readBuf = (byte[]) msg.obj;
                if(transSPP != null){
                	
                	int i = 0;
                	for(i=0;i<arg1;i++){
                		
                		try {
    						transSPP.spp_recv_lock.acquire(1);
    					} catch (InterruptedException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
                		{
	                		try {
	                			Log.i(tag, "recv:"+readBuf[i]);
								transSPP.spp_recv_data.put(readBuf[i]);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                		transSPP.spp_recv_cnt.release(1);
                		}
                		transSPP.spp_recv_lock.release(1);
                	}
                	
                	
                	
                }
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                
                break;
            case MESSAGE_TOAST_CONN_LOST:
            	mClassicConnected = false;
            	downloadBtn.setEnabled(false);
            	erasedBtn.setEnabled(false);
            	use_eraseBtn.setEnabled(false);
                Toast.makeText(context, msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
                

            }
        }
    };
	
    @SuppressLint("HandlerLeak")
	private final Handler mSppOtaHandler = new Handler(){
    	
    	@Override
        public void handleMessage(Message msg) {
    		switch (msg.what) {
    		case MESSAGE_SPP_OTA_SUCCESS:
    			downloadBtn.setEnabled(true);
    			erasedBtn.setEnabled(true);
    			use_eraseBtn.setEnabled(true);
    			pb.setVisibility(ProgressBar.INVISIBLE);
    			Toast.makeText(getActivity(), "File transmit over successfully!", Toast.LENGTH_SHORT).show();
    			break;
    		case MESSAGE_SPP_OTA_FAILED:
    			downloadBtn.setEnabled(true);
    			erasedBtn.setEnabled(true);
    			use_eraseBtn.setEnabled(true);
    			pb.setVisibility(ProgressBar.INVISIBLE);
    			String tt = "" + msg.arg1;
    			Toast.makeText(getActivity(), "File transmit failed!\n Error Code :"+tt, Toast.LENGTH_SHORT).show();
    			break;
    			
    		case MESSAGE_PBAR_INI:
    			int len1 = msg.arg1;
				pb.setMax(len1);
    			break;
    			
    		case MESSAGE_UPDATE_PBAR:
    			int len11 = msg.arg1;
				pb.setProgress(len11);
    			break;
    		case MESSAGE_ERASE_SUCCESS:
    			downloadBtn.setEnabled(true);
    			erasedBtn.setEnabled(true);
    			use_eraseBtn.setEnabled(true);
    			Toast.makeText(getActivity(), "Erase config data successfull!", Toast.LENGTH_SHORT).show();
    			break;
    			
    		case MESSAGE_ERASE_FAILED:
    			downloadBtn.setEnabled(true);
    			erasedBtn.setEnabled(true);
    			use_eraseBtn.setEnabled(true);
    			String tmp = "Erase config data error!\n\nError code "+msg.arg1;
    			Toast.makeText(getActivity(), tmp, Toast.LENGTH_SHORT).show();
    			break;
    		}
    	}
    };
	//classic scan result
	private static IntentFilter classicUpdateIntentFilter() {
	    final IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
	    return intentFilter;
	}
	
	private BroadcastReceiver searchDevices = new BroadcastReceiver() { 
	
	   public void onReceive(Context context, Intent intent) {
	
	       String action = intent.getAction();
	
	       Bundle b = intent.getExtras();
	
	       Object[] lstName = b.keySet().toArray(); 
	
	       // 显示所有收到的消息及其细节
	
		   for (int i = 0; i < lstName.length; i++) {
		
		      String keyName = lstName[i].toString();
		
		      Log.e(keyName, String.valueOf(b.get(keyName)));
		
		   }
	
		   //搜索设备时，取得设备的MAC地址
		
		   if (BluetoothDevice.ACTION_FOUND.equals(action)) {
		
			   	BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			   	//添加表
				mDeviceListAdapter.addDevice(device);
				mDeviceListAdapter.notifyDataSetChanged();
		        
		
		   }
		   
	   }
	
	};
	
	
	    
	private void scanDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mClassicAdapter.cancelDiscovery();
                }
            }, SCAN_PERIOD);

            mScanning = true;
            boolean res = mClassicAdapter.startDiscovery();
            if(!res)
            {
            	Log.i(tag, "discovery error!");
            }
        } else {
            mScanning = false;
            mClassicAdapter.cancelDiscovery();
        }
    }    
	
	
	//classic spp connect 
	private void ConnectDevice()
	{
		if (mChatService != null) {
	        // Only if the state is STATE_NONE, do we know that we haven't started already
	        if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
	        	// Start the Bluetooth chat services
	        	mChatService.start();
	        }
	        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) 
	        {
	        	BluetoothDevice device = mClassicAdapter.getRemoteDevice(mDeviceAddress);
	        	mChatService.connect(device, true);
	        	mDevice = device;
			}
	    }else
	    {
	    	Toast.makeText(context, "mChatService is null", Toast.LENGTH_SHORT).show();
	    }
	 
	}
	
	private void initUI(final View root) {
		root.setClickable(true);
		root.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {}
		});
		pb = (ProgressBar) root.findViewById(R.id.progressBar);
		tv = (TextView) root.findViewById(R.id.textView);
		lv = (ListView) root.findViewById(R.id.list_device);
		downloadBtn = (Button) root.findViewById(R.id.downloadBtn);
		erasedBtn = (Button) root.findViewById(R.id.eraseBtn);
		downloadBtn.setEnabled(false);
		erasedBtn.setEnabled(false);
		
		appBtn = (Button) root.findViewById(R.id.applicationBtn);
		// delete 
		use_eraseBtn = (Button) root.findViewById(R.id.user_erase);
		use_eraseBtn.setVisibility(View.INVISIBLE);
		use_eraseBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				byte[] cmd = {(byte) 0xBC, (byte) 0xA4, (byte) 0xBB, (byte) 0xEE, 0x4F, 0x54, 0x41, (byte) 0xC9, (byte) 0xFD, (byte) 0xBC, (byte) 0xB6};
				if(transSPP != null)
					transSPP.hs_write(cmd, cmd.length);
//				CommCmd hs_comm = new CommCmd(transSPP);
//				hs_comm.ResetMCU();
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Log.i("MCU", "user erase");
				scanDevice(true);
				downloadBtn.setEnabled(false);
        		erasedBtn.setEnabled(false);
        		use_eraseBtn.setEnabled(false);
			}
			
		});
		/*delete */
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				final BluetoothDevice device = mDeviceListAdapter.getDevice(position);
		        if (device == null) return;
		        if (mScanning) {
		        	
		        	scanDevice(false);
		            mScanning = false;
		        }
		        mDeviceAddress = device.getAddress();		   
		        // TODO add cassic device connect 
		        ConnectDevice();
		        
		        mDeviceListAdapter.clear();
		        mDeviceListAdapter.notifyDataSetChanged();
		        
			}
			
		});
		
		root.findViewById(R.id.button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				root.setClickable(false);
				ViewPropertyAnimator.animate(root)
				.rotationY(-90).setDuration(200)
				.setListener(new AnimatorListenerAdapter(){
					@Override
					public void onAnimationEnd(Animator animation) {
						root.clearAnimation();
						root.setVisibility(View.GONE);
						view.setEnabled(true);
					}
				});
				
				if(mScanning)
        			scanDevice(false);
        	
				if(mClassicConnected)
				{
					//TODO disconnect classic device 
					if(mChatService != null)
						mChatService.stop();
				}
				downloadBtn.setEnabled(false);
            	erasedBtn.setEnabled(false);
            	use_eraseBtn.setEnabled(false);
				mDeviceListAdapter.clear();
	        	mDeviceListAdapter.notifyDataSetChanged();
			}
		});
		
		
		//scan
		root.findViewById(R.id.scanBtn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mDeviceListAdapter.clear();
            	mDeviceListAdapter.notifyDataSetChanged();
            	if(mChatService.getState() == mChatService.STATE_CONNECTED)
            	{
            		mChatService.stop();
            	}
            	
            	
        		if(mconnectedDevices != null)
            		for(BluetoothDevice device : mconnectedDevices){
    					mDeviceListAdapter.addDevice(device);
    					mDeviceListAdapter.notifyDataSetChanged();
    				}
        		pb.setProgress(0);
        		pb.setVisibility(ProgressBar.INVISIBLE);
        		downloadBtn.setEnabled(false);
        		erasedBtn.setEnabled(false);
        		use_eraseBtn.setEnabled(false);
        		scanDevice(false);
        		scanDevice(true);
            	
            	
            	
			}
		});
		//file select 
		appBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showFileChooser(APP_FILE_SELECT_CODE);
			}
			
		});
		//download
		downloadBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//TODO
				downloadBtn.setEnabled(false);
        		erasedBtn.setEnabled(false);
        		use_eraseBtn.setEnabled(false);
				pb.setVisibility(ProgressBar.VISIBLE);

				
				try {
					Thread.sleep(10);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {

						
						Utils op = new Utils();
						if(m_appfile_uri == null)
						{
							if(mSppOtaHandler != null)
								mSppOtaHandler.obtainMessage(SPPOTAFragment.MESSAGE_SPP_OTA_FAILED, -1, -1, null).sendToTarget();
						}
						String file_path = GetPathFromUri4kitkat.getPath(context, m_appfile_uri);
						byte[] dataBuf;
						try {
							//do_work_on_boads.app_buf = op.readSDFile(file_path);
							dataBuf = op.readSDFile(file_path);
							
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							return ;
						}
						if(dataBuf == null )
						{
							Toast.makeText(getActivity(), "Read the application file failed!", Toast.LENGTH_SHORT)
							.show();
							return;
						}
						CommCmd hs_comm = new CommCmd(transSPP);
						int res = hs_comm.startDownload(dataBuf, dataBuf.length, mSppOtaHandler);
						if(res == 0)
						{
							if(mSppOtaHandler != null)
								mSppOtaHandler.obtainMessage(SPPOTAFragment.MESSAGE_SPP_OTA_SUCCESS, -1, -1, null).sendToTarget();
//							byte[] cmd = SppCommandPacket.getResetMCUCtrlPacket_0();
//							transSPP.hs_write(cmd, cmd.length);
//							try {
//								Thread.sleep(1);
//							} catch (InterruptedException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//							byte[] cmd_1 = SppCommandPacket.getResetMCUCtrlPacket_0();
//							transSPP.hs_write(cmd_1, cmd_1.length);
							hs_comm.ResetMCU();
						}else
						{
							if(mSppOtaHandler != null)
								mSppOtaHandler.obtainMessage(SPPOTAFragment.MESSAGE_SPP_OTA_FAILED, res, -1, null).sendToTarget();
						}
					}
				}).start();
			}
		});
		
		//erase
		erasedBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//TODO
				erasedBtn.setEnabled(false);
				downloadBtn.setEnabled(false);
				use_eraseBtn.setEnabled(false);
				new Thread(new Runnable() {
					
					@Override
					public void run() {
		            	int res;         
		            	byte[] buf = new byte[256];
		            	byte[] resbuf = new byte[256];
		            	CommCmd hs_comm = new CommCmd(transSPP);
						res = hs_comm.SendCmd(CommCmd.COMM_CMD_ERASE_ALLCONFIGDATA, buf, (byte)1, resbuf, (byte) 4);
						if(res == 0){
							if(mSppOtaHandler != null)
								mSppOtaHandler.obtainMessage(SPPOTAFragment.MESSAGE_ERASE_SUCCESS, -1, -1, null).sendToTarget();
						}
						else{
							
							if(mSppOtaHandler != null)
								mSppOtaHandler.obtainMessage(SPPOTAFragment.MESSAGE_ERASE_FAILED, res, -1, null).sendToTarget();
						}
					}
				}).start();
				
				
				//delete
//				byte[] cmd = {(byte) 0xBC, (byte) 0xA4, (byte) 0xBB, (byte) 0xEE, 0x4F, 0x54, 0x41, (byte) 0xC9, (byte) 0xFD, (byte) 0xBC, (byte) 0xB6};
//				if(transSPP != null)
//					transSPP.hs_write(cmd, cmd.length);
//				try {
//					Thread.sleep(100);
//				} catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				Log.i("MCU", "user erase");
//				scanDevice(true);
				//delete
			}
		});
				
		
		
		ViewHelper.setRotationY(view, 0);
		ViewHelper.setRotationY(root, -90);
		root.setVisibility(View.VISIBLE);
		
		ViewPropertyAnimator.animate(view).rotationY(90)
		.setDuration(300).setListener(null)
		.setInterpolator(new AccelerateInterpolator());
		
		
		ViewPropertyAnimator.animate(root)
		.rotationY(0).setDuration(200).setStartDelay(300)
		.setListener(new AnimatorListenerAdapter() {
			@Override
			public void onAnimationEnd(Animator animation) {
				ViewHelper.setRotationY(view, 0);
			}
		});
	}
	
	/** 根据返回选择的文件，来进行上传操作 **/
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == Activity.RESULT_OK) {
			// Get the Uri of the selected file
			Uri uri = data.getData();
			String file_path = uri.getEncodedPath();
			file_path = uri.getLastPathSegment();
			//file_path = uri.getPathSegments();
			file_path = uri.getPath();
			String fileName = file_path.substring(file_path.lastIndexOf("/") + 1);
//			Toast.makeText(getActivity(), uri.toString(), Toast.LENGTH_SHORT)
//			.show();
			if(requestCode == APP_FILE_SELECT_CODE){
				m_appfile_uri = uri;//.toString();
				EditText et =  (EditText) root.findViewById(R.id.applicationText);
				et.setText("");
				et.setText(fileName);
			}
		}
			//test{
//			Utils op = new Utils();
//			file_path = GetPathFromUri4kitkat.getPath(context, uri);
//			try {
//				byte[] buf = op.readSDFile(file_path);
//				int len = buf.length;
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			//}
	
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	/** 调用文件选择软件来选择文件 **/
	private void showFileChooser(int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("*/*");
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		try {
			startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
					requestCode);
		} catch (android.content.ActivityNotFoundException ex) {
			// Potentially direct the user to the Market with a Dialog
			Toast.makeText(getActivity(), "请安装文件管理器", Toast.LENGTH_SHORT)
					.show();
		}
	}
	
	public void show(final View view,Bundle bundle){
		view.setEnabled(false);
		this.view = view;
		
		if(root == null)
			return ;
		
		ViewHelper.setRotationY(view, 0);
		ViewHelper.setRotationY(root, -90);
		root.setVisibility(View.VISIBLE);
		
		ViewPropertyAnimator.animate(view).rotationY(90)
		.setDuration(300).setListener(null)
		.setInterpolator(new AccelerateInterpolator());
		
		
		ViewPropertyAnimator.animate(root)
		.rotationY(0).setDuration(200).setStartDelay(300)
		.setListener(new AnimatorListenerAdapter() {
			@Override
			public void onAnimationEnd(Animator animation) {
				ViewHelper.setRotationY(view, 0);
			}
		});
	}
}
